﻿<template>
    <full-screen-dialog :title="titleMap[mode]" v-model="visible" :width="1200" destroy-on-close>
        <el-form :model="entityObj" :rules="rules" ref="dialogForm" label-width="100px">
            <el-steps :active="active" align-center finish-status="success">
                <el-step :title="item" description v-for="item in stepList" :key="item.index" />
            </el-steps>

            <el-row style="margin-top: 24px;">
                <el-col :span="8">
                    <el-form-item label-width="120px" label="单据状态:">{{entityObj.statusDesc}}</el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="物料状态:">{{entityObj.taskStatusDesc}}</el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item
                        label-width="120px"
                        label="单据金额:"
                    >{{entityObj.totalAmount}}元 = 要货金额:{{entityObj.materialFee}}元+其他费用:{{entityObj.otherFee}}元</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="要货编号:">{{entityObj.applyOrderCode}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="要货时间:">{{entityObj.applyDate}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="期望到货时间:">{{entityObj.expectedDate}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="要货单位:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.realName}}
                                <br />
                                联系电话:{{entityObj.mobile}}
                                <br />
                                收货地址:{{entityObj.address}}
                            </template>
                            <span style="color: blue;">{{entityObj.storeName}}</span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="供货单位:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.purchaseRealName}}
                                <br />
                                联系电话:{{entityObj.purchaseMobile}}
                                <br />
                                联系地址:{{entityObj.purchaseAddress}}
                            </template>
                            <span style="color: blue;">{{entityObj.purchaseUnityName}}</span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="申请人:">{{entityObj.applyName}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="申请时间:">{{entityObj.applyDate}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="最后修改人:">{{entityObj.updateName}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="最后修改时间:">{{entityObj.updateTime}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="附件:" v-if="entityObj.applyFile">
                        <sc-upload-file
                            v-model="entityObj.applyFile"
                            :objName="'Supply/ApplyOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            disabled
                            :limit="1"
                        />
                    </el-form-item>
                    <el-form-item label-width="120px" label="附件:" v-else>无</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注:">
                        <!-- {{entityObj.remarks}} -->
                        <el-collapse v-model="activeNames" style="width: 100%;">
                            <div class="collapse-container">
                                <div class="collapse-header" @click="toggleCollapse">
                                    <span></span>
                                    <div style="display: flex;align-items: center;">
                                        <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                                        <img
                                            v-if="isCollapsed"
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                                        />
                                        <img
                                            v-else
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                                        />
                                    </div>
                                </div>
                            </div>
                            <div v-show="!isCollapsed" class="collapse-content1">
                                <sc-editor
                                    ref="scRemarks"
                                    v-model="entityObj.remarks"
                                    :toolbar="[]"
                                    :statusbar="false"
                                    :height="300"
                                    style="width: 100%;"
                                ></sc-editor>
                            </div>
                        </el-collapse>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="要货清单:">
                        <scTable
                            ref="applyDetailTable"
                            :data="entityObj.applyOrderItems"
                            :border="true"
                            tableName="applyOrderDetail"
                            hidePagination="false"
                            hideRefresh="false"
                            :style="entityObj.applyOrderItems?.length>10?'height: 500px;width: 100%;':'height:'+entityObj.applyOrderItems?.length*50 +' px;width: 100%;'"
                            :column="columnDetailList"
                            :row-class-name="setRowClass"
                            :cell-class-name="getColumnClassName"
                            show-summary
                            :summary-method="getSummaries"
                            :span-method="arraySpanMethod"
                            highlight-current-row
                        >
                            <template #materialName="{row}">
                                <div
                                    style="color: #318cf2;"
                                    v-if="row.materialImages && row.materialImages.length > 0"
                                    @click="handlePreview(row) "
                                >{{row.materialName}}</div>
                                <div v-else>{{row.materialName}}</div>
                            </template>
                            <template
                                #qty="{row}"
                            >{{row.purchaseSaleType==2||row.purchaseSaleType==3?"无": row.qty}}</template>
                            <template #supplierName="{row}">{{row.supplierName}}</template>
                            <template #purchaseSaleTypeDesc="{row}">{{row.purchaseSaleTypeDesc}}</template>
                            <template #deliveryQty="{row}">
                                <span v-if="row.receiveStatus==1">{{row.deliveryQty}}</span>
                                <span v-else>/</span>
                            </template>
                            <template #deliveryAmt="{row}">
                                <span v-if="row.receiveStatus==1">{{row.deliveryQty*row.price}}</span>
                                <span v-else>/</span>
                            </template>
                            <template #purchaseAmt="{row}">
                                <span v-if="row.receiveStatus==1">{{row.purchaseAmt}}</span>
                                <span v-else>/</span>
                            </template>
                        </scTable>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="审核备注:">{{entityObj.auditRemarks}}</el-form-item>
                </el-col>
            </el-row>

            <!-- <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="赠送清单:">
                        <el-table
                            :data="entityObj.giveOrderItems"
                            :border="true"
                            style="width: 100%"
                            :row-class-name="tableRowClassName"
                        >
                            <el-table-column label="物料编码" prop="materialCode" width="110"/>
                            <el-table-column label="物料名称" prop="materialName" width="180"/>
                            <el-table-column label="分类" prop="materialTypeName" width="160"/>
                            <el-table-column label="规格" prop="materialSpecs" width="160"/>
                            <el-table-column label="单位" prop="unitName" width="110"/>
                            <el-table-column label="赠送数量" prop="qty" width="110"/>
                            <el-table-column label="配送单价" prop="price" width="110"/>
                            <el-table-column label="金额" prop="totalAmount" width="110"/>
                            <el-table-column label="备注" prop="remarks" width="140"/>
                            <el-table-column label="供应商" prop="supplierName" width="160" v-if="orgType==1"/>
                            <el-table-column label="配送数量" prop="deliveryQty" width="120"/>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>-->

            <!-- <el-row style="margin-top: 24px;">
                <el-col :span="8">
                    <el-form-item label-width="120px" label="结款方式:">{{entityObj.statusDesc}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="状态:">{{entityObj.taskStatusDesc}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="应收款项:">接单金额: - 破损退款金额: =</el-form-item>
                </el-col>
            </el-row>-->
        </el-form>

        <!-- 预览组件 -->
        <el-image-viewer
            v-if="showImage"
            @close="closeViewer"
            :hide-on-click-modal="true"
            :url-list="srcList"
        />
    </full-screen-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            orgType: 2,
            stepList: ["门店已下单", "接单处理中", "已完成"],
            active: 1,
            tableRowClassName: "warning-row",
            tableRowClassName1: "success-row",
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            columnDetailList: [
                {
                    prop: "materialName",
                    label: "物料名称",
                    width: "150",
                    sortable: true,
                },
                {
                    prop: "materialSpecs",
                    label: "规格",
                    width: "140",
                    sortable: true,
                },
                {
                    prop: "unitName",
                    label: "单位",
                    width: "80",
                    sortable: true,
                },
                {
                    prop: "qty",
                    label: "要货数量",
                    width: "105",
                    sortable: true,
                },
                {
                    prop: "price",
                    label: "销售单价",
                    width: "105",
                    sortable: true,
                },
                {
                    prop: "thirdPrice",
                    label: "分销价格",
                    width: "105",
                    hide: this.orgType != 1&&this.orgType!= 4,
                    sortable: true,
                },
                {
                    prop: "totalAmount",
                    label: "要货金额",
                    width: "105",
                    sortable: true,
                },
                {
                    prop: "supplierName",
                    label: "供应商",
                    width: "140",
                    sortable: true,
                },
                {
                    prop: "purchaseSaleTypeDesc",
                    label: "模式",
                    width: "110",
                    sortable: true,
                },
                {
                    prop: "purchaseQty",
                    label: "下单数量",
                    width: "105",
                    hide: this.orgType != 1,
                    sortable: true,
                },
                {
                    prop: "deliveryQty",
                    label: "接单数量",
                    width: "105",
                    sortable: true,
                },
                {
                    prop: "purchaseAmt",
                    label: "接单金额",
                    hide: this.orgType!=1,
                    width: "105",
                    sortable: true,
                },
                {
                    prop: "deliveryAmt",
                    label: "销售金额",
                    width: "105",
                    sortable: true,
                },
                {
                    prop: "receiveStatusDesc",
                    label: "接单状态",
                    width: "110",
                    sortable: true,
                },
                {
                    prop: "remarks",
                    label: "备注",
                    width: "140",
                    sortable: true,
                },
                {
                    prop: "materialCode",
                    label: "物料编码",
                    width: "140",
                    sortable: true,
                },
                {
                    prop: "materialTypeName",
                    label: "分类",
                    width: "140",
                    sortable: true,
                },
            ],
            entityObj: {
                purchaseProtocolId: 0,
                purchaseProtocolCode: "",
                purchaseProtocolName: "",
                status: 1,
                crName: "",
                crDate: "",
                supplier: {},
                protocolDate: [],
                purchaseUnityName: "",
                remarks: "",
                protocolFile: "",
                purchaseProtocolItems: [],
                giveOrderItems: [],
            },
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            materialState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,

            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseSaleType: [],
            suppliers: [],
            selectionRows: [],
            isCollapsed: true, // 初始状态为收起
        };
    },
    computed: {},
    methods: {
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //图片预览
        handlePreview(row) {
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            this.showImage = false;
        },
        //表单注入数据
        async setData(data) {
            this.entityObj = {};
            this.stepList = ["门店已下单", "接单处理中", "已完成"];
            // console.log("红红火火恍恍惚惚哈哈哈哈哈哈",this.entityObj)
            const returnValue = await this.$API.auth.GetProcessApi.get(
                `apply-order/${data.applyOrderId}`,
                {}
            );
            if (returnValue.status == 200) {
                this.entityObj = { ...returnValue.response };
                console.log("要货明细", this.entityObj);
                switch (this.entityObj.status) {
                    case 0:
                    case 1:
                    case 2:
                    case 9:
                        this.stepList = [
                            "门店已下单",
                            this.entityObj.statusDesc,
                        ];
                        this.active = 2;
                        break;
                    case 3:
                    case 4:
                        this.active = 1;
                        break;
                    case 5:
                        this.active = 2;
                        break;
                    case 8:
                        this.active = 3;
                        break;
                    default:
                        this.active = 1;
                        break;
                }
            }

            // const materialItemIds = data.applyOrderItems.map(
            //     (p) => p.materialItemId
            // );
            // const returnValue = await this.$API.auth.PostProcessApi.post(
            //     "purchase-protocol/suppliers",
            //     { materialItemIds: materialItemIds }
            // );

            // if (returnValue.status == 200) {
            //     this.suppliers = returnValue.response;
            //     const _this = this;

            //     data.applyOrderItems.map((p) => {
            //         const suppliers = _this.suppliers.filter(
            //             (t) => t.materialItemId == p.materialItemId
            //         );

            //         p.purchases.map((t) => {
            //             t.suppliers = suppliers;
            //             t.purchaseSaleType = this.optionsPurchaseSaleType.find(
            //                 (p) => p.value == t.purchaseSaleType
            //             ).value;
            //         })

            //         if (p.purchases && p.purchases.length == 0) {
            //             p.purchases.push({
            //                 suppliers: suppliers,
            //                 supplierId:
            //                     suppliers && suppliers.length > 0
            //                         ? suppliers[0].supplierId
            //                         : null,
            //                 qty: p.qty,
            //                 price:
            //                     suppliers && suppliers.length > 0
            //                         ? suppliers[0].price
            //                         : 0.0,
            //                 totalAmount:
            //                     p.qty *
            //                     (suppliers && suppliers.length > 0
            //                         ? suppliers[0].price
            //                         : 0.0),
            //                 purchaseSaleType: this.optionsPurchaseSaleType.find(
            //                     (p) => p.value == 0
            //                 ).value,
            //             });
            //         }
            //     });

            //     this.entityObj = {
            //         ...data,
            //         applyOrderItems: [...data.applyOrderItems],
            //         giveOrderItems: [...data.giveOrderItems],
            //     };
            // }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["PurchaseSaleType"] }
                );
                if (returnValue.status == 200) {
                    this.optionsPurchaseSaleType = returnValue.response.find(
                        (p) => p.code == "PurchaseSaleType"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }

                let filteredData = data.filter(
                    (item) => item.receiveStatus != 9
                );
                let values = filteredData.map((item) =>
                    Number(item[column.property])
                );
                // 过滤掉 receiveStatus != 1 的行
                if (
                    column.property == "deliveryAmt" ||
                    column.property == "deliveryQty" ||
                    column.property == "purchaseAmt"
                ) {
                    const filteredData = data.filter(
                        (item) => item.receiveStatus == 1
                    );
                    values = filteredData.map((item) =>
                        Number(item[column.property])
                    );
                }

                if (
                    column.property == "qty" ||
                    column.property == "totalAmount" ||
                    column.property == "deliveryQty" ||
                    column.property == "purchaseQty" ||
                    column.property == "purchaseAmt"
                ) {
                    if (!values.every((item) => isNaN(item))) {
                        const total = values.reduce((a, b) => a + b, 0);
                        sums[index] = total;
                    }
                } else if (column.property == "deliveryAmt") {
                    var totalAmount = 0;
                    if (this.entityObj.applyOrderItems) {
                        filteredData.forEach((item) => {
                            totalAmount += item.price * item.deliveryQty;
                        });
                    }
                    sums[index] = totalAmount;
                }
            });
            return sums;
        },
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            // 获取当前行的id值
            const currentId = row.sourceApplyOrderItemId;
            if (
                column.property === "materialCode" ||
                column.property === "materialName" ||
                column.property === "materialSpecs" ||
                column.property == "materialTypeName" ||
                column.property === "unitName" ||
                column.property === "qty" ||
                column.property === "price" ||
                column.property === "thirdPrice" ||
                column.property === "totalAmount" 
            ) {
                if (
                    rowIndex + 1 < this.entityObj.applyOrderItems.length &&
                    this.entityObj.applyOrderItems[rowIndex + 1]
                        .sourceApplyOrderItemId === currentId
                ) {
                    return {
                        rowspan: 2,
                        colspan: 1,
                    };
                }

                if (
                    rowIndex > 0 &&
                    this.entityObj.applyOrderItems[rowIndex - 1]
                        .sourceApplyOrderItemId === currentId
                ) {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                }
            }

            return {
                rowspan: 1,
                colspan: 1,
            };
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
        setRowClass({ row, rowIndex }) {
            let rowClass = "";
            if (this.selectionRows.includes(row)) {
                rowClass += " selected-row-color";
            }

            // //终止
            // if (row.receiveStatus == 9) {
            //     rowClass += " selected-row-color-grey";
            // }
            return rowClass;
        },
        getColumnClassName({ row, column, rowIndex, columnIndex }) {
            let rowClass = "";
           
            if (
                column.property === "supplierName" ||
                column.property === "purchaseSaleTypeDesc" ||
                column.property === "purchaseQty" ||
                column.property ==  "deliveryQty" ||
                column.property ==  "deliveryAmt" ||
                column.property === "purchaseAmt" ||
                column.property === "receiveStatusDesc" ||
                column.property === "remarks"
            ) {
                 //终止
                if (row.receiveStatus == 9) {
                    rowClass += " selected-row-color-grey";
                }
            } else {
                if (!this.entityObj.applyOrderItems.some((p) => p.sourceApplyOrderItemId ==row.sourceApplyOrderItemId && p.receiveStatus != 9)) {
                    rowClass += " selected-row-color-grey";
                }

                rowClass += " row-back-color";
            }

            return rowClass;
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        console.log('orgType',this.orgType!=1)
    
        await this.initOptions();
    },
};
</script>

<style scoped>
.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .selected-row-color {
    background-color: #b8dcff !important;
}

.el-table .selected-row-color-grey {
    color: #000000 !important;
    text-decoration: line-through; /* 删除线 */
}

.row-back-color {
    background-color: #0b57d0 !important;
}

.el-form-item {
    margin-bottom: 8px !important;
}

.collapse-container {
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    padding: 10px 10px 10px 0;
    margin-bottom: 10px;
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 5px;
    padding-left: 0;
    font-weight: bold;
    font-size: 12px;
}
.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}

/* 单元格容器 */
.cell-container {
    position: relative;
    display: inline-block;
}

/* 单元格内容的样式 */
.cell-content {
    padding-left: 20px; /* 确保单元格内容不被飘带遮挡 */
}

/* 飘带的样式 */
.ribbon {
    position: absolute;
    top: 0;
    left: 0;
    background: #ff4d4f;
    color: white;
    padding: 2px 8px;
    border-radius: 2px;
    font-size: 7px;
    font-weight: bold;
    text-align: center;
    transform: rotate(-30deg); /* 使飘带倾斜 */
    white-space: nowrap;
    width: 60px; /* 飘带宽度 */
    height: 100px !important;
    line-height: 1.5; /* 文字垂直居中 */
}

/* 飘带的尖角 */
.ribbon::before {
    content: "";
    position: absolute;
    top: 0;
    left: -20px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #ff4d4f;
}

/* 根据 type 自定义飘带颜色 */
.ribbon-newbie {
    background: #67c23a; /* 新手飘带颜色 */
}

.ribbon-advanced {
    background: #409eff; /* 高级飘带颜色 */
}

.ribbon-expert {
    background: #f56c6c; /* 专家飘带颜色 */
}

/* 文字颜色 */
.ribbon-text {
    color: white;
}
</style>
